import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import * as authApi from '@/api/auth'
import type { User, UserLoginRequest, UserRegisterRequest, UserUpdateRequest } from '@/types/api'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref<string>(localStorage.getItem('token') || '')
  const user = ref<User | null>(null)
  const loading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!user.value)

  // 登录
  const login = async (loginData: UserLoginRequest) => {
    try {
      loading.value = true
      const response = await authApi.login(loginData)
      
      token.value = response.token
      user.value = response.user
      
      // 保存到本地存储
      localStorage.setItem('token', response.token)
      localStorage.setItem('user', JSON.stringify(response.user))
      
      ElMessage.success('登录成功')
      return response
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 注册
  const register = async (registerData: UserRegisterRequest) => {
    try {
      loading.value = true
      const response = await authApi.register(registerData)
      ElMessage.success('注册成功，请登录')
      return response
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取用户资料
  const fetchProfile = async () => {
    try {
      const profile = await authApi.getProfile()
      user.value = { ...user.value, ...profile } as User
      localStorage.setItem('user', JSON.stringify(user.value))
      return profile
    } catch (error) {
      console.error('获取用户资料失败:', error)
      throw error
    }
  }

  // 更新用户资料
  const updateProfile = async (profileData: UserUpdateRequest) => {
    try {
      loading.value = true
      const updatedUser = await authApi.updateProfile(profileData)

      // 更新本地用户信息
      user.value = { ...user.value, ...updatedUser } as User
      localStorage.setItem('user', JSON.stringify(user.value))

      return updatedUser
    } catch (error) {
      console.error('更新用户资料失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = async () => {
    try {
      if (token.value) {
        await authApi.logout()
      }
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 清除本地状态
      token.value = ''
      user.value = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      ElMessage.success('已退出登录')
    }
  }

  // 初始化用户状态
  const initAuth = () => {
    const savedUser = localStorage.getItem('user')
    if (savedUser && token.value) {
      try {
        user.value = JSON.parse(savedUser)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        logout()
      }
    }
  }

  return {
    // 状态
    token,
    user,
    loading,
    // 计算属性
    isLoggedIn,
    // 方法
    login,
    register,
    fetchProfile,
    updateProfile,
    logout,
    initAuth
  }
})
